<template>
  <div class="container">
    <FmTable ref="fmTable" url="/process/generator" id="id" tableName="datasourceconfig" :columns="columns"
             :toolbar="['add','del']">
      <template #opt="scope">
        <el-button link type="primary" size="small" @click="openConnect(scope.row)">连接</el-button>
        <el-button link type="primary" size="small" @click="fmTable.handleEdit(scope.$index, scope.row)">修改</el-button>
      </template>
    </FmTable>
    <el-dialog
        title="数据库连接"
        v-model="datasourceDlgShow"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
    >
      <el-form
          ref="datasourceForm"
          :model="datasourceFormData"
          :rules="datasourceRule"
          label-width="120px"
      >
        <el-form-item label="数据库类型">
          <el-select
              v-model="datasourceFormData.dbType"
              filterable
              default-first-option
          >
            <el-option
                v-for="item in fmTable.dict('DB_TYPE')"
                :key="item.value"
                :label="item.label"
                :value="toStrOrInt(datasourceFormData.dbType,item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库描述" prop="dbDesc">
          <el-input v-model="datasourceFormData.dbDesc" placeholder="数据库描述" show-word-limit maxlength="64"/>
        </el-form-item>
        <el-form-item label="Host" prop="host">
          <el-input v-model="datasourceFormData.host" placeholder="地址" show-word-limit maxlength="100"/>
        </el-form-item>
        <el-form-item label="Port" prop="port">
          <el-input v-model="datasourceFormData.port" placeholder="端口" show-word-limit maxlength="10"/>
        </el-form-item>
        <el-form-item :label="dbNamePlaceholder" prop="dbName">
          <el-input v-model="datasourceFormData.dbName" :placeholder="dbNamePlaceholder" show-word-limit
                    maxlength="64"/>
        </el-form-item>
        <el-form-item label="连接类型" v-show="showOracleFields">
          <el-select v-model="datasourceFormData.oracleConnType">
            <el-option
                v-for="item in oracleConnTypeList"
                :key="item.val"
                :label="item.lab"
                :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="showPgSqlSchema" :label="schemaPlaceholder" :prop="schemaPlaceholder">
          <el-input v-model="datasourceFormData.schemaName" :placeholder="schemaPlaceholder+',如SCOTT'" show-word-limit
                    maxlength="64"/>
        </el-form-item>
        <el-form-item label="Username" prop="username">
          <el-input v-model="datasourceFormData.username" placeholder="用户名" show-word-limit maxlength="100"/>
        </el-form-item>
        <el-form-item label="角色" v-show="showOracleFields">
          <el-select v-model="datasourceFormData.oracleRole" clearable>
            <el-option
                v-for="item in oracleRoleList"
                :key="item.val"
                :label="item.lab"
                :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Password" prop="password">
          <el-input v-model="datasourceFormData.password" type="password" placeholder="密码" show-word-limit
                    maxlength="100"/>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onDatasourceTest(datasourceForm)">测试连接</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {fetchData, delData, saveorUpadateDate, deteleAllData} from '@/api';
import {ref, reactive, onMounted,computed} from "vue";
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import {useRouter} from "vue-router";


let router = useRouter()
let tableData = ref([])
let groupTitle = ref('')
let groupDlgShow = ref(false)
let datasourceDlgShow = ref(false)
let formData = reactive({
  id: 0,
  groupName: ''
})
let datasourceForm = ref(null)
const fmTable=ref(null)
const columns = [
  {
    "label": "数据库编号",//标签名称
    "index": "id",//数据库索引
    "rules": [
      {required: true, message: "请输入主键", trigger: "blur",},
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
    "addable": false,
    "upd-disabled":true
  },
  {
    "label": "数据库类型",//标签名称
    "index": "dbType",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "type": "dict",
    "dictkey": "DB_TYPE",
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "数据库驱动",//标签名称
    "index": "driverClass",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "数据库描述",//标签名称
    "index": "dbDesc",//数据库索引
    "rules": [
    ],//值规则
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "数据库名称",//标签名称
    "index": "dbName",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "数据库主机",//标签名称
    "index": "host",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "search": true,//是否是搜索表单
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "数据库端口",//标签名称
    "index": "port",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "用户名",//标签名称
    "index": "username",//数据库索引
    "rules": [
      {required: true, message: '不能为空', trigger: 'blur'}
    ],//值规则
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "label": "密码",//标签名称
    "index": "password",//数据库索引
    "rules": [
    ],//值规则
    "dataType": "text",//值值类型默认字符类型
  },
  {
    "type": "opt",//普通行，字典行，自定义行
    "label": "操作",//标签名称
    "index": "opt",//数据库索引
    "rules": [],//值规则
    "width": 150,
    "dataType": "text",//值值类型默认字符类型
  }

]

let oracleConnTypeList = ref([{
  lab: "服务名",
  val: 1
}, {
  lab: "SID",
  val: 2
}])
let oracleRoleList = ref([{
  lab: "default",
  val: ""
}, {
  lab: "SYSDBA",
  val: 1
}, {
  lab: "SYSOPER",
  val: 2
}])
const DB_TYPE = {
  MySQL: "1",
  Oracle: "2",
  SQL_Server: "3",
  PostgreSQL: "4",
  Dm: "5"
}
let datasourceRule = {
  host: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  port: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  username: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ],
  dbName: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ]
}
const datasourceFormData = ref({
  id: 0,
  dbGroupName: '',
  dbType: "1",
  dbDesc: '',
  host: '',
  port: '',
  username: '',
  password: '',
  dbName: '',
  oracleConnType: '',
  oracleRole: '',
  schemaName: '',
  packageName: '',
  delPrefix: '',
  groupId: '',
  author: ''
})
const showPgSqlSchema = computed(() => {
  return datasourceFormData.value.dbType === DB_TYPE.PostgreSQL || datasourceFormData.value.dbType === DB_TYPE.Oracle;
})
const dbNamePlaceholder = computed(() => {
  if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
    return "服务名";
  } else {
    return "数据库";
  }
})
const schemaPlaceholder = computed(() => {
  if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
    return "数据库";
  } else {
    return "schema";
  }
})
const openConnect = (row:any) => {
  row.dbType=row.dbType.toString()
  datasourceDlgShow.value=true
  datasourceFormData.value=row
}
const toStrOrInt=((formdata:any,item:any)=>{
  return (typeof formdata==='string')?item:parseInt(item)
})
const showOracleFields = computed(() => {
  debugger
  return datasourceFormData.value.dbType === DB_TYPE.Oracle;
})
const packageOracleFields = () => {
  // 处理oracle连接数据
  if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
    // 处理连接类型
    if (datasourceFormData.value.oracleConnType == 1) {
      datasourceFormData.value.dbName = "/" + datasourceFormData.value.dbName;
    } else if (datasourceFormData.value.oracleConnType == 2) {
      datasourceFormData.value.dbName = ":" + datasourceFormData.value.dbName;
    }
    // 处理账号角色
    if (datasourceFormData.value.oracleRole == 1) {
      datasourceFormData.value.username += " AS SYSDBA";
    } else if (datasourceFormData.value.oracleRole == 2) {
      datasourceFormData.value.username += " AS SYSOPER";
    }
  }
}
const unPackOracleFields = (item: any) => {
  // 处理oracle属性 拆包
  if (item.dbType === DB_TYPE.Oracle) {
    // 处理连接类型
    if (item.dbName.startsWith("/")) {
      item.oracleConnType = 1;
      item.dbName = item.dbName.replace("/", "");
    } else if (item.dbName.startsWith(":")) {
      item.oracleConnType = 2;
      item.dbName = item.dbName.replace(":", "");
    }
    // 处理账号角色
    if (item.username.includes("AS SYSDBA")) {
      item.oracleRole = 1;
      item.username = item.username.replace(" AS SYSDBA", "");
    } else if (item.username.includes("AS SYSOPER")) {
      item.oracleRole = 2;
      item.username = item.username.replace(" AS SYSOPER", "");
    }
  }
}

const onDatasourceTest = (form: any) => {
  packageOracleFields();
  form.validate((valid) => {
    if (valid) {
      saveorUpadateDate('/process/generator/datasourceconfig/test', datasourceFormData.value).then(resp => {
        if (datasourceFormData.value.dbType === DB_TYPE.Oracle) {
          // 处理连接类型
          if (datasourceFormData.value.oracleConnType == 1) {
            datasourceFormData.value.dbName = datasourceFormData.value.dbName.replace("/", "");
          } else if (datasourceFormData.value.oracleConnType == 2) {
            datasourceFormData.value.dbName = datasourceFormData.value.dbName.replace(":", "");
          }
          // 处理账号角色
          if (datasourceFormData.value.oracleRole == 1) {
            datasourceFormData.value.username = datasourceFormData.value.username.replace(" AS SYSDBA", "");
          } else {
            datasourceFormData.value.username = datasourceFormData.value.username.replace(" AS SYSOPER", "");
          }
        }
        ElMessage.success('连接成功')
      }, err => {
        unPackOracleFields(datasourceFormData.value);
      })
    }
  })
}


</script>
